#include "natiavwidget.h"
#include "compixmap.h"
#include "natiavscanlog.h"
#include "natiavtrustdialog.h"
#include "natiavisolationdilog.h"
#include "antivirus/antiviruswork.h"
#include "updatedialog.h"
#include "cominfo.h"
#include "widgets/custompushbutton.h"
#include "widgets/dialogmanage.h"
#include "customfiledialog.h"
#include "common/scanwhitelist/scanwhitelist.h"
#include "common/schedulescan/schedulescandialog.h"
#include "invokers/invokerfactory.h"
#include "antivirus/usbscansettingdlg.h"
#include "widgets/dspinner.h"

#include "widgets/hiconlistview.h"

//#include <DFontSizeManager>
//#include <DApplicationHelper>
#include <QListView>
#include <QFileDialog>
#include <QSize>
#include <QSysInfo>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <QMessageBox>
#include <QTreeView>
#include <QDialogButtonBox>
//#include <QStandardPaths>


#define VERSION "current-version" //当前版本
#define VERSION_CONFING "version.conf" //版本配置文件
#define MAIN_WIDTH 660 //页面宽度
#define TITLE_HEIDTH 135 //上部分高度
#define CENTER_HEIDTH 300 //中间高度
#define BUTTOM_HEIDTH 65 //下面高度
#define DIALOG_WIDTH 380 //dialog  宽度
#define DIALOG_HEIGHT 145 //dialog  高度
#define DIALOG_PB_WIDTH 140 //dialog  按钮宽度
#define DIALOG_PB_HEIGHT 36 //dialog  按钮高度
#define VDB_INIT_VERSION "20.8.18.14" //病毒库初使版本
#define LEFT_MARGINS 40 //左边距
#define TOP_MARGINS 0 //上边距
#define RIGHT_MARGINS 0 //右边距离
#define BUTTOM_MARGINS 0 //下边距离
#define TITLE_LEFT_MARGINS 0 //左边距
#define TITLE_TOP_MARGINS 40 //上边距
#define TITLE_RIGHT_MARGINS 0 //右边距离
#define TITLE_BUTTOM_MARGINS 0 //下边距离
#define SPACING 5 //布局间隙
#define AREA_ICON_SIZE 16 //信任，隔离区域图标大小
#define ENGIN_ICON_SIZE 26 //引擎图标大小
#define TEXTELIDELEN_BOTTOM 70 //界面底部字体裁减长度
#define TEXTELIDELEN_TOP 320 //界面顶部字体裁减长度

#define SET_ACC_NAME(control, name) SET_ACCESS_NAME(control, natiavWidget, name)

NatiavWidget::NatiavWidget(AntiVirusWork *work, QWidget *parent)
    : QWidget(parent)
    , m_logDialog(nullptr)
    , m_trustDialog(nullptr)
    , m_isolationDialog(nullptr)
    , m_timeLable(nullptr)
    , m_version(nullptr)
    , m_updateBtn(nullptr)
    , m_isbVdbUpdating(false)
    , m_spinner(nullptr)
//    , m_guiHelper(DGuiApplicationHelper::instance())
    , m_updateFialFlag(false)
    , m_antivirusWork(work)
    , m_enginIcon(nullptr)
    , m_enginLable(nullptr)
    , m_scanLogButton(nullptr)
    , m_isolationButton(nullptr)
    , m_trustAreaButton(nullptr)
    , m_scanWhitelistButton(nullptr)
    , m_isolationflag(false)
    , m_truestFlag(false)
    , m_isolationSize(0)
    , m_trustSize(0)
{
    m_hmiScreen = InvokerFactory::GetInstance().CreateInvoker("com.deepin.defender.hmiscreen",
                                                              "/com/deepin/defender/hmiscreen",
                                                              "com.deepin.defender.hmiscreen",
                                                              ConnectType::SESSION, this);

    // 初始化安全中心gsetting配置
    m_gsetting = InvokerFactory::GetInstance().CreateSettings("com.deepin.dde.deepin-defender", QByteArray(), this);

    setObjectName("NatiavWidget");
    //初始化布局
    initGUI();
    // 初始化信号槽链接
    initConnect();
    // 更新界面
    updateUI();

    // 初始化时，如果正在检查更新，则转圈
    if (m_antivirusWork->vdbVersionChecking()) {
        updataCheckingWaiting();
    }

    // 控件注册事件
    m_enginIcon->installEventFilter(this);
    m_enginLable->installEventFilter(this);

    installEventFilter(this);

//    if (DSysInfo::UosType::UosServer != SystemType) {
        QString sSystemArch = m_antivirusWork->getSystemArch();
        // 安恒只有amd架构彩显示可点击图标，瑞星amd\arm\mips显示可点击图标
        if (EnginType::Ahprotector == m_antivirusWork->getVriusType()
            && ARCH_AMD == sSystemArch) {
            m_enginIcon->setCursor(QCursor(Qt::PointingHandCursor));
            m_enginLable->setCursor(QCursor(Qt::PointingHandCursor));
        } else if (EnginType::Rising == m_antivirusWork->getVriusType()
                   && (ARCH_AMD == sSystemArch
                       || ARCH_ARM == sSystemArch
                       || ARCH_MIPS == sSystemArch
                       || ARCH_LOONGARCH == sSystemArch)) {
            m_enginIcon->setCursor(QCursor(Qt::PointingHandCursor));
            m_enginLable->setCursor(QCursor(Qt::PointingHandCursor));
        }
//    } else {
//        m_enginIcon->setVisible(false);
//        m_enginLable->setVisible(false);
//    }
}

//展现日志页面
void NatiavWidget::showScanLog()
{
    if (m_logDialog) {
        delete m_logDialog;
        m_logDialog = nullptr;
    }
    m_logDialog = new NatiavScanLog(this);
    SET_ACC_NAME(m_logDialog, logDialog);
    m_logDialog->raise();
    m_logDialog->show();
    m_logDialog->getlogData();
}

//展现信任区域
void NatiavWidget::showScanTrust()
{
    //如果在版本更新中  提示更新提示
    if (m_isbVdbUpdating) {
        showUpdateTip();
    } else {
        // 判断信任区弹窗是否开启
        if (m_trustDialog) {
            m_trustDialog->deleteLater();
            m_trustDialog = nullptr;
        }
        m_trustDialog = new NatiavTrustDialog(m_antivirusWork, this);
        SET_ACC_NAME(m_trustDialog, trustDialog);
        m_antivirusWork->requestQueryTrustFiles();
        //查询信任文件结果给 信任页面
        connect(this, SIGNAL(onNotifyQueryTrustFile(QList<TrustFileInfo>)), m_trustDialog, SLOT(receptionTrustFile(QList<TrustFileInfo>)));
        // 更新信任区域的数量
        connect(m_trustDialog, SIGNAL(notifyUpdateTrustSize()), m_antivirusWork, SLOT(selectTrustAreaSize()));

        //删除信任文件
        connect(m_trustDialog, SIGNAL(requsetRemoveTrustFile(QString)), this, SLOT(doRemoveTrustFile(QString)));
        m_trustDialog->raise();
        m_trustDialog->show();
    }
}

//隔离区也 弹框
void NatiavWidget::showIsolation()
{
    if (m_isbVdbUpdating) {
        //如果在版本更新中  提示更新提示
        showUpdateTip();
    } else {
        // 判断隔离区弹窗是否开启
        if (m_isolationDialog) {
            delete m_isolationDialog;
            m_isolationDialog = nullptr;
        }
        m_isolationDialog = new NatiavIsolationDilog(m_antivirusWork, this);
        SET_ACC_NAME(m_isolationDialog, showIsolationDialog);
        m_antivirusWork->requestQueryIsolationFile();
        //查询隔离文件结果给 隔离页面显示
        connect(this, SIGNAL(onNotifyQueryIsolationFile(QList<TrustFileInfo>)), m_isolationDialog, SLOT(receptionIsolationFile(QList<TrustFileInfo>)));
        // 更新信任区域的数量
        connect(m_isolationDialog, SIGNAL(notifyUpdateIsolationSize()), m_antivirusWork, SLOT(selectIsolationAreaSize()));
        //删除隔离文件
        connect(m_isolationDialog, SIGNAL(requestRemoveIsolationFile(QString)), this, SLOT(doRemoveIsolationFile(QString)));
        m_isolationDialog->raise();
        m_isolationDialog->show();
    }
}

// 展现白名单
void NatiavWidget::showScanWhitelist()
{
    // 扫描白名单弹框
    ScanWhiteList *scanWhitelist = new ScanWhiteList(this);
    scanWhitelist->raise();
    scanWhitelist->show();
}

// 展现定时扫描
void NatiavWidget::showScheduleScanSetting()
{
    ScheduleScanDialog *scheduleScanSetting = new ScheduleScanDialog(this);
    scheduleScanSetting->raise();
    scheduleScanSetting->show();
}

void NatiavWidget::showUSBScanSetting()
{
    USBScanSettingDlg *usbScanSettingDlg = new USBScanSettingDlg(this);
    usbScanSettingDlg->raise();
    usbScanSettingDlg->show();
}

// 安恒/瑞星图标点击跳转应用商店
void NatiavWidget::jumpToAppStore()
{
    m_antivirusWork->jumpToAppStore();
}

//开始扫描弹窗
void NatiavWidget::showCustomScan()
{
    // 文件列表
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::DirectoryOnly);
//    dialog.setAllowMixedSelection(true);
    dialog.setAcceptMode(QFileDialog::AcceptOpen);

    QString historyDir = "";
    if (historyDir.isEmpty()) {
        historyDir = QDir::homePath();
    }
    dialog.setDirectory(historyDir);
    if (QDialog::Accepted == dialog.exec()) {
        QStringList dirlist = dialog.selectedFiles();
        if (!dirlist.isEmpty()) {
            // 判断当前状态 再次判定  就是为了避免右键查杀
            ScanStatus current = m_antivirusWork->getCurrentScanStatus();
            if (ScanStatus::Free == current) {
                QString filepath;
                // 遍历文件列表 然后拼接
                for (int i = 0; i < dirlist.size(); i++) {
                    filepath += dirlist.at(i) + "*";
                }
                // 去掉最后一个 * 号
                filepath = filepath.remove(filepath.size() - 1, 1);
                Q_EMIT onNotifyShowScan(2, filepath, m_sLocalVdbVersion);
            } else {
                // 展现正在扫描对话框
                showTipDialog();
            }
        }
    }
}

//提示弹框
void NatiavWidget::showUpdateTip()
{
    // 病毒库更新提示
    DialogManage dialog;
    dialog.showNormalTipDialog(IconNormal, TipUpdate);
    return;
}

// 提示弹窗
void NatiavWidget::showTipDialog()
{
    ScanStatus currentStatus = m_antivirusWork->getCurrentScanStatus();
    // 根据不同的状态提示不同的提示语
    DialogManage dialog;
    switch (currentStatus) {
    case UsbScanning:
        // 提示usb 正在扫描中 只能出现一个提示语相同的弹窗
        dialog.showNormalTipDialog(IconTip, TipUsbScaning);
        break;
    case HomePageScanning:
        // 提示首页正体检在快速查杀中
        dialog.showNormalTipDialog(IconTip, TipHomeChecking);
        break;
    case HomePageResult:
        // 首页有异常场没有处理提示框
        dialog.showNormalTipDialog(IconTip, TipHomeThreats);
        break;
    case HomePageFixing:
        // 首页正在修复中提示框
        dialog.showNormalTipDialog(IconTip, TipHomeFixing);
        break;
    case VdbUpdating:
        // 病毒库更新提示
        dialog.showNormalTipDialog(IconTip, TipUpdate);
        break;
    case Scanning:
    case Pausing:
    case ResultThreats:
    case ResultNoThreats:
        // 病毒库更新提示
        dialog.showNormalTipDialog(IconTip, TipThreatScaning);
        break;
    default:
        break;
    }
}

//设置因主题改变图标
void NatiavWidget::setIconByThemeChange()
{
    // 判断当前主题类型
//    if (m_guiHelper->themeType() == DGuiApplicationHelper::ColorType::LightType) {
        // 如果是浅色主题
        m_scanLogButton->setIcon(QIcon(":/icons/deepin/builtin/actions/dcc_antiav_scanLogs_16px.svg"));
        m_isolationButton->setIcon(QIcon(":/icons/deepin/builtin/actions/dcc_antiav_quarantine_16px.svg"));
        m_trustAreaButton->setIcon(QIcon(":/icons/deepin/builtin/actions/dcc_antiav_whitelist_16px.svg"));
        m_scanWhitelistButton->setIcon(QIcon(":/icons/deepin/builtin/icons/def_Icon_Whitelist_16px.svg"));
//    } else {
        // 设色主题
//        m_scanLogButton->setIcon(QIcon::fromTheme(ANTIAV_LOG_DARK));
//        m_isolationButton->setIcon(QIcon::fromTheme(ANTIAV_QUARANTINE_DARK));
//        m_trustAreaButton->setIcon(QIcon::fromTheme(ANTIAV_TRUST_DARK));
//        m_scanWhitelistButton->setIcon(QIcon::fromTheme(ANTIAV_WHITELIST_LIGHT));
//    }
}

// 更新信任区数量
void NatiavWidget::updateTrustAreaSize(int size)
{
    m_truestFlag = true;
    // 更新信任区数量
    m_trustSize = size;
    refreshTrustAreaElideText(QString::number(m_trustSize));
}

// 更新隔离区域数量
void NatiavWidget::updateIsolationAreaSize(int size)
{
    m_isolationflag = true;
    m_isolationSize = size;
    refreshIsolationElideText(QString::number(m_isolationSize));
}

//初始化界面
void NatiavWidget::initGUI()
{
    //垂直布局
    QVBoxLayout *m_mainLayout = new QVBoxLayout;

    m_mainLayout->setSpacing(SPACING);
    //四周边距
    m_mainLayout->setContentsMargins(LEFT_MARGINS, TOP_MARGINS, RIGHT_MARGINS, BUTTOM_MARGINS);
    //上布局
    QWidget *titleWidget = new QWidget(this);
    SET_ACC_NAME(titleWidget, titleWidget);
    //titleWidget->setFixedHeight(TITLE_HEIDTH);
    titleWidget->setMinimumWidth(MAIN_WIDTH);
    titleWidget->setLayout(initTitle());
    m_mainLayout->addWidget(titleWidget, 0, Qt::AlignLeft);

    //三种查杀  全盘  快速  自定义
    QWidget *ConterWidget = new QWidget(this);
    SET_ACC_NAME(ConterWidget, conterWidget);
    //ConterWidget->setFixedHeight(CENTER_HEIDTH);
    ConterWidget->setMinimumWidth(MAIN_WIDTH);
    //中间布局
    ConterWidget->setLayout(initCenter());
    m_mainLayout->addStretch();
    m_mainLayout->addWidget(ConterWidget, 0, Qt::AlignCenter | Qt::AlignLeft);

    //日志 信任区 隔离区
    QWidget *bottomWidget = new QWidget(this);
    SET_ACC_NAME(bottomWidget, bottomWidget);
    //bottomWidget->setFixedHeight(BUTTOM_HEIDTH);
    bottomWidget->setMinimumWidth(MAIN_WIDTH);
    //下面布局
    bottomWidget->setLayout(initBottom());
    m_mainLayout->addStretch();
    m_mainLayout->addWidget(bottomWidget, 0, Qt::AlignBottom | Qt::AlignLeft);
    //设置布局
    setLayout(m_mainLayout);

    // 触发更新信任区域和隔离区
    m_antivirusWork->selectTrustAreaSize();
    m_antivirusWork->selectIsolationAreaSize();
}

//中间的布局
QHBoxLayout *NatiavWidget::initCenter()
{
    //按钮水平布局
    QHBoxLayout *m_blayout = new QHBoxLayout;
    //四周边距
    m_blayout->setContentsMargins(0, 0, 0, 50);
    m_blayout->setSpacing(SPACING);

    HIconListView* centerView = new HIconListView(this);
    centerView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    centerView->setMinimumWidth(MAIN_WIDTH);
    centerView->setFrameShape(QFrame::Shape::NoFrame);

    //按钮  中间标题
    QStringList titles;
    titles << tr("Full Scan") << tr("Quick Scan") << tr("Custom Scan");
    //按钮图标
    QStringList icons;
    icons << ":/icons/deepin/builtin/actions/dcc_antiav_all1_96px.svg"
          << ":/icons/deepin/builtin/actions/dcc_antiav_quick1_96px.svg"
          << ":/icons/deepin/builtin/actions/dcc_antiav_customer1_96px.svg";

    QList<HIconListViewItem> items;
    for (int i = 0; i < titles.size(); ++i) {
        HIconListViewItem item;
        item.setIcon(QIcon(icons[i]));
        item.setText(titles[i]);
        items.append(item);
    }
    centerView->setItems(items);

    connect(centerView, SIGNAL(itemClicked(int)), this, SLOT(displayCenteridget(int)));

    m_blayout->addWidget(centerView);
    return m_blayout;
}

//下面按钮布局
QVBoxLayout *NatiavWidget::initBottom()
{
    //垂直布局
    QVBoxLayout *vlayout = new QVBoxLayout;
    vlayout->setContentsMargins(0, 10, 0, 5);
    vlayout->setSpacing(0);

    //第一行布局
    QHBoxLayout *hlayout = new QHBoxLayout;
    hlayout->setContentsMargins(0, 0, 0, 0);
    hlayout->setSpacing(8);
    // 左边布局
    m_scanLogButton = new CustomPushbutton(this);
    SET_ACC_NAME(m_scanLogButton, scanLogButton);
    refreshScanLogElideText();
    int result = 0;
    m_isolationButton = new CustomPushbutton(this);
    SET_ACC_NAME(m_isolationButton, isolationButton);
    refreshIsolationElideText(QString::number(result));
    m_trustAreaButton = new CustomPushbutton(this);
    SET_ACC_NAME(m_trustAreaButton, trustAreaButton);
    refreshTrustAreaElideText(QString::number(result));

    // 扫描白名单
    m_scanWhitelistButton = new CustomPushbutton(this);
    m_scanWhitelistButton->setText(tr("Whitelist"));

    SET_ACC_NAME(m_scanWhitelistButton, trustAreaButton);

    // 设置图标
    setIconByThemeChange();

    hlayout->addWidget(m_scanLogButton, 0, Qt::AlignLeft | Qt::AlignVCenter);
    hlayout->addSpacing(2);
    hlayout->addWidget(m_isolationButton, 0, Qt::AlignLeft | Qt::AlignVCenter);
    hlayout->addSpacing(2);
    hlayout->addWidget(m_trustAreaButton, 0, Qt::AlignLeft | Qt::AlignVCenter);
    hlayout->addSpacing(2);
    hlayout->addWidget(m_scanWhitelistButton, 0, Qt::AlignLeft | Qt::AlignVCenter);
    hlayout->addStretch();

    // 右侧版本描述
    QLabel *lable = new QLabel(this);
    SET_ACC_NAME(lable, dbLable);
    //病毒库版本
    lable->setText(tr("Virus database"));
    //版本
    m_version = new QLabel(this);
    SET_ACC_NAME(m_version, versionLabel);
    m_version->setText("25.00.00.15");
    QFont ft = m_version->font();
    ft.setPixelSize(12);
    m_version->setFont(ft);
    lable->setFont(ft);
    hlayout->addWidget(lable, 0, Qt::AlignRight);
    hlayout->addWidget(m_version, 0, Qt::AlignRight | Qt::AlignVCenter);
    //加载 控件
    m_spinner = new DSpinner(this);
    SET_ACC_NAME(m_spinner, spinner);
    m_spinner->setFixedSize(QSize(15, 15));
    m_spinner->hide();
    hlayout->addWidget(m_spinner, 0, Qt::AlignRight);

    m_updateBtn = new QCommandLinkButton("", this);
    SET_ACC_NAME(m_updateBtn, updateBtn);
    m_updateBtn->setFont(ft);
    //    DFontSizeManager::instance()->bind(m_updateBtn, DFontSizeManager::T8);
    hlayout->addWidget(m_updateBtn, 0, Qt::AlignRight);

    // 第二行病毒引擎信息
    QHBoxLayout *hlayout5 = new QHBoxLayout;
    hlayout5->setContentsMargins(0, 0, 5, 0);
    hlayout5->setSpacing(10);
    m_enginIcon = new QLabel(this);
    SET_ACC_NAME(m_enginIcon, enginIcon);
    m_enginLable = new QLabel(this);
    SET_ACC_NAME(m_enginLable, enginLable);
//    DFontSizeManager::instance()->bind(m_enginLable, DFontSizeManager::T10);
    // 判断不同病毒引擎
    if (EnginType::Rising == m_antivirusWork->getVriusType()) {
        m_enginIcon->setPixmap(QIcon(":/icons/deepin/builtin/actions/dcc_rising_logo_26px.svg").pixmap(QSize(73, 10)));
        m_enginLable->setText(tr("Supported by Rising"));
    } else {
        m_enginIcon->setPixmap(QIcon(":/icons/deepin/builtin/actions/dcc_Ahprotector_log_26px.svg").pixmap(QSize(10, 13)));
        m_enginLable->setText(tr("Supported by DAS-security"));
    }
    hlayout5->addStretch(0);
    hlayout5->addWidget(m_enginIcon, 0, Qt::AlignRight | Qt::AlignVCenter);
    hlayout5->addWidget(m_enginLable, 0, Qt::AlignRight | Qt::AlignVCenter);

    vlayout->addStrut(0);
    vlayout->addLayout(hlayout);
    vlayout->addLayout(hlayout5);
    return vlayout;
}

//标题布局
QVBoxLayout *NatiavWidget::initTitle()
{
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->setContentsMargins(TITLE_LEFT_MARGINS, TITLE_TOP_MARGINS, TITLE_RIGHT_MARGINS, TITLE_BUTTOM_MARGINS);
    mainLayout->setSpacing(SPACING);

    QHBoxLayout *middleLayout = new QHBoxLayout;
    middleLayout->setContentsMargins(0, 0, 0, 0);
    middleLayout->setSpacing(0);

    QVBoxLayout *leftLayout = new QVBoxLayout;
    leftLayout->setContentsMargins(0, 0, 0, 0);
    leftLayout->setSpacing(0);

    //标题   定期杀毒，保障安全
    m_titleLable = new QLabel(this);
    SET_ACC_NAME(m_titleLable, titleLable);
    QFont ft = m_titleLable->font();
    ft.setBold(true);
    m_titleLable->setFont(ft);
//    DFontSizeManager::instance()->bind(m_titleLable, DFontSizeManager::T5);
    leftLayout->addWidget(m_titleLable);

    //上次更新的时间
    QString stTime = "2020/03/24 14:10";
    m_timeLable = new QLabel;
    SET_ACC_NAME(m_timeLable, timeLable);
    QString strUpdateTime = tr("The virus database is up to date. Last update: %1").arg(stTime);
    QFont ft1 = m_timeLable->font();
    ft1.setBold(false);
    m_timeLable->setFont(ft1);
    refreshTopPanelElideText(strUpdateTime);
    // 字体样式
    QPalette pal;
    pal.setColor(QPalette::Text, QColor("#526A7F"));
    m_timeLable->setPalette(pal);
//    DFontSizeManager::instance()->bind(m_timeLable, DFontSizeManager::T8);
    leftLayout->addSpacing(11);
    leftLayout->addWidget(m_timeLable);
    middleLayout->addLayout(leftLayout);

    QLabel *scheduleIconLabel = new QLabel;
    scheduleIconLabel->setPixmap(QIcon(":/icons/deepin/builtin/actions/icon_schedulescan_16px.svg").pixmap(QSize(16, 16)));
    m_scheduleScanLabel = new QLabel(tr("Schedule Scan"));
//    DFontSizeManager::instance()->bind(m_scheduleScanLabel, DFontSizeManager::T6);
    m_scheduleScanLabel->installEventFilter(this);

    QFrame *vline = new QFrame();
    SET_ACC_NAME(vline, vlineFrame);
    //竖线
    vline->setObjectName(QString("vline"));
    vline->setFixedHeight(16);
    vline->setFrameShape(QFrame::VLine);
    vline->setFrameShadow(QFrame::Sunken);

    QLabel *USBScanIconLabel = new QLabel;
    USBScanIconLabel->setPixmap(QIcon(":/icons/deepin/builtin/actions/icon_usbscan_16px.svg").pixmap(QSize(16, 16)));
    m_usbAutoScanLabel = new QLabel(tr("USB Device Scan"));
//    DFontSizeManager::instance()->bind(m_usbAutoScanLabel, DFontSizeManager::T6);
    m_usbAutoScanLabel->installEventFilter(this);

    // 服务器屏蔽USB扫描
//    if (DSysInfo::UosType::UosServer == SystemType) {
//        vline->setVisible(false);
//        USBScanIconLabel->setVisible(false);
//        m_usbAutoScanLabel->setVisible(false);
//    }

    middleLayout->addStretch(1);
    middleLayout->addWidget(scheduleIconLabel);
    middleLayout->addSpacing(8);
    middleLayout->addWidget(m_scheduleScanLabel);
    middleLayout->addSpacing(10);
    middleLayout->addWidget(vline);
    middleLayout->addSpacing(10);
    middleLayout->addWidget(USBScanIconLabel);
    middleLayout->addSpacing(8);
    middleLayout->addWidget(m_usbAutoScanLabel);

    m_usbAutoScanButton = new HSwitchButton;
    m_usbAutoScanButton->setChecked(m_gsetting->GetValue(AUTO_SCAN_USB).toBool());

    QFrame *line = new QFrame(this);
    SET_ACC_NAME(line, lineFrame);
    //横线
    line->setObjectName(QString("line"));
    line->setGeometry(QRect(80, 100, 500, 3));
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);

    mainLayout->addLayout(middleLayout);
    mainLayout->addSpacing(30);
    mainLayout->addWidget(line);

    return mainLayout;
}

//中间布局点击
void NatiavWidget::displayCenteridget(const QModelIndex & nIndex)
{

}

void NatiavWidget::displayCenteridget(int nIndex)
{
    //快速查询路径
    QString quick = "/usr/bin*/usr/sbin*/usr/local*/tmp";
    ScanStatus current = m_antivirusWork->getCurrentScanStatus();
    // 判断是否在更新中
    if (m_isbVdbUpdating) {
        showUpdateTip();
    } else {
        //　如果第一次信任区和隔离区域都刷新　　并且在空闲状态　　表示当前服务没有任何操作
        if (m_truestFlag && m_isolationflag && ScanStatus::Free == current) {
            // 空闲状态才会扫描
            switch (nIndex) {
            case AllKilling:
                //去moudule 跳转的动作
                Q_EMIT onNotifyShowScan(0, "/", m_sLocalVdbVersion);
                break;
            case QuickKilling:
                //去moudule 跳转的动作
                Q_EMIT onNotifyShowScan(1, quick, m_sLocalVdbVersion);
                break;
            case CustomKilling:
                showCustomScan();
                break;
            default:
                break;
            }
            // 更新上次扫描时间
            m_antivirusWork->updateLastScanningTime();
        } else {
            // 根据类型展现不同提示框
            showTipDialog();
        }
    }
}

// 事件过滤
bool NatiavWidget::eventFilter(QObject *obj, QEvent *event)
{
    // 判断是否鼠标点击
    if (event->type() == QEvent::MouseButtonPress) {
        // 判断是否在那个对象上面
        if ((m_enginIcon == obj) || (m_enginLable == obj)) {
            jumpToAppStore();
        } else if (m_usbAutoScanLabel == obj) {
            showUSBScanSetting();
        } else if (m_scheduleScanLabel == obj) {
            //在此处理定时扫描鼠标点击事件
            showScheduleScanSetting();
        }
    }
    if (this == obj) {
        // 如果当前是字体改变的事件
        if (event->type() == QEvent::FontChange) {
            refreshScanLogElideText();
            refreshIsolationElideText(QString::number(m_isolationSize));
            refreshTrustAreaElideText(QString::number(m_trustSize));
            refreshTopPanelElideText(m_strLastUpdateTime);
        }
    }
    return QWidget::eventFilter(obj, event);
}

// 初始化链接
void NatiavWidget::initConnect()
{
    // 检查更新/更新按钮点击槽
    connect(m_updateBtn, SIGNAL(clicked(bool)), this, SLOT(updateButtonClicked()));
    // 主题变换
//    connect(m_guiHelper, SIGNAL(themeTypeChanged(ColorType)), this, SLOT(themeTypeChange(ColorType)));

    // work 跟扫描模块主页模块 信号链接
    // 连接请求更新病毒查杀首页数据信号
    connect(m_antivirusWork, SIGNAL(notifyUpdateAntiVirusHomeUI()), this, SLOT(updateUI()));
    connect(m_antivirusWork, SIGNAL(notifyVirusImportUpdataUi(const QString)), this, SLOT(updateVersionUI(const QString)));
    // 查询信任的结果
    connect(m_antivirusWork, SIGNAL(sendTrustFilesByList(QList<TrustFileInfo>)), this, SLOT(doQueryTrustFile(QList<TrustFileInfo>)));
    // 查询隔离文件的结果
    connect(m_antivirusWork, SIGNAL(sendIsolationFilesByList(QList<TrustFileInfo>)), this, SLOT(doQueryIsolationFile(QList<TrustFileInfo>)));
    // 查询隔离文件的结果
    connect(m_antivirusWork, SIGNAL(notifyUpdateTrustAreaSize(int)), this, SLOT(updateTrustAreaSize(int)));
    // 查询隔离文件的结果
    connect(m_antivirusWork, SIGNAL(notifyUpdateIsolationAreaSize(int)), this, SLOT(updateIsolationAreaSize(int)));

    // 扫描模块首页的主页对扫描日志  信任区  隔离区 三个弹窗的信号链接
    // 扫描日志
    connect(m_scanLogButton, SIGNAL(clicked()), this, SLOT(showScanLog()));
    // 隔离区域
    connect(m_isolationButton, SIGNAL(clicked()), this, SLOT(showIsolation()));
    // 信任区域
    connect(m_trustAreaButton, SIGNAL(clicked()), this, SLOT(showScanTrust()));
    // 扫描白名单
    connect(m_scanWhitelistButton, SIGNAL(clicked()), this, SLOT(showScanWhitelist()));
    //USB自动扫描
    connect(m_usbAutoScanButton, SIGNAL(statusChanged(bool)), this, SLOT(usbAutoScan(bool)));
}

void NatiavWidget::refreshScanLogElideText()
{
    QFontMetrics fontmet(m_scanLogButton->getButtonFont());
    QString removeText = tr("Scan Logs");
    QString elidedStr = fontmet.elidedText(removeText, Qt::TextElideMode::ElideMiddle, TEXTELIDELEN_BOTTOM);
    m_scanLogButton->setText(elidedStr);
    if (fontmet.width(removeText) > TEXTELIDELEN_BOTTOM) {
        m_scanLogButton->setToolTip(tr("Scan Logs"));
    } else {
        m_scanLogButton->setToolTip("");
    }
}

void NatiavWidget::refreshIsolationElideText(const QString &size)
{
    QFontMetrics fontmet(m_isolationButton->getButtonFont());
    QString removeText = tr("Quarantine (%1)").arg(size);
    QString elidedStr = fontmet.elidedText(removeText, Qt::TextElideMode::ElideMiddle, TEXTELIDELEN_BOTTOM);
    m_isolationButton->setText(elidedStr);
    if (fontmet.width(removeText) > TEXTELIDELEN_BOTTOM) {
        m_isolationButton->setToolTip(tr("Quarantine (%1)").arg(size));
    } else {
        m_isolationButton->setToolTip("");
    }
}

void NatiavWidget::refreshTrustAreaElideText(const QString &size)
{
    QFontMetrics fontmet(m_trustAreaButton->getButtonFont());
    QString removeText = tr("Exclusions (%1)").arg(size);
    QString elidedStr = fontmet.elidedText(removeText, Qt::TextElideMode::ElideMiddle, TEXTELIDELEN_BOTTOM);
    m_trustAreaButton->setText(elidedStr);
    if (fontmet.width(removeText) > TEXTELIDELEN_BOTTOM) {
        m_trustAreaButton->setToolTip(tr("Exclusions (%1)").arg(size));
    } else {
        m_trustAreaButton->setToolTip("");
    }
}

void NatiavWidget::refreshTopPanelElideText(const QString &strMsg)
{
    QFont font = m_timeLable->font();
    QFontMetrics fontmet(font);
    QString elidedStr = fontmet.elidedText(strMsg, Qt::TextElideMode::ElideMiddle, TEXTELIDELEN_TOP);
    m_timeLable->setText(elidedStr);

    if (fontmet.width(strMsg) > TEXTELIDELEN_TOP) {
        m_timeLable->setToolTip(strMsg);
    } else {
        m_timeLable->setToolTip("");
    }

    m_strLastUpdateTime = strMsg;

    font = m_titleLable->font();
    fontmet = QFontMetrics(font);
    QString strTitle = tr("Scan virus regularly to remove any threats");
    elidedStr = fontmet.elidedText(strTitle, Qt::TextElideMode::ElideMiddle, TEXTELIDELEN_TOP);
    m_titleLable->setText(elidedStr);

    if (fontmet.width(strTitle) > TEXTELIDELEN_TOP) {
        m_titleLable->setToolTip(strTitle);
    } else {
        m_titleLable->setToolTip("");
    }
}

//查询出的信任文件信息    转发给信任弹窗页面
void NatiavWidget::doQueryTrustFile(QList<TrustFileInfo> sInfos)
{
    Q_EMIT onNotifyQueryTrustFile(sInfos);
}

//查询隔离文件
void NatiavWidget::doQueryIsolationFile(QList<TrustFileInfo> sPaths)
{
    Q_EMIT onNotifyQueryIsolationFile(sPaths);
}

//移除隔离文件
void NatiavWidget::doRemoveIsolationFile(QString sPath)
{
    m_antivirusWork->requestChangeIsolationFile(false, sPath);
}

//移除信任文件
void NatiavWidget::doRemoveTrustFile(QString sPath)
{
    m_antivirusWork->requestChangeTrustFiles(false, sPath);
}

// 主题的改变
void NatiavWidget::themeTypeChange(ColorType themeType)
{
    Q_UNUSED(themeType);
    // 设置图标
    setIconByThemeChange();
}

void NatiavWidget::updateUI()
{
    // 获取是否处于病毒更新状态
    m_isbVdbUpdating = m_antivirusWork->vdbUpdating();
    // 获取服务器病毒库版本
    m_sSrvVdbVersion = m_antivirusWork->srvVdbVersion();
    // 获取本地病毒库版本
    m_sLocalVdbVersion = m_antivirusWork->localVdbVersion();
    // 是否需要更新
    bool needUpdate = m_antivirusWork->needUpdateVersion();
    // 获取上次扫描时间
    QString sLastScanningTime = m_antivirusWork->lastScanningTime();

    // 更新顶部扫描提示
    if (!needUpdate) {
        if (sLastScanningTime == "-1") {
            refreshTopPanelElideText(tr("The virus database is up to date. Start a scan please."));
        } else {
            //如果是显示   病毒库已经最新  上次查杀时间
            refreshTopPanelElideText(tr("The virus database is up to date. Last scan: %1").arg(sLastScanningTime));
        }
    } else {
        if (sLastScanningTime == "-1") {
            refreshTopPanelElideText(tr("The virus database is not up to date. Update first and start a scan please."));
        } else {
            //病毒库不是最新，上次更新时间
            refreshTopPanelElideText(tr("The virus database is not up to date. Last scan: %1").arg(sLastScanningTime));
        }
    }

    // 更新底部扫描提示
    m_version->setText(m_sLocalVdbVersion);
    m_version->show();
    m_spinner->stop();
    m_spinner->hide();
    m_updateBtn->setVisible(true);

    // 根据病毒库是否最新，设置底部控件隐藏与显示
    if (!needUpdate) {
        m_updateBtn->setText(tr("Check for updates"));
        m_updateBtn->setProperty("flag", 0);
    } else {
        m_updateBtn->setText(tr("Update"));
        m_updateBtn->setProperty("flag", 1);
    }

    if (m_isbVdbUpdating) {
        m_updateBtn->setVisible(false);
        m_spinner->start();
        m_spinner->show();
    }

    // 触发更新信任区域和隔离区
    m_antivirusWork->selectTrustAreaSize();
    m_antivirusWork->selectIsolationAreaSize();
}

// 确认更新病毒库
void NatiavWidget::confirmUpdateVdb()
{
    // 如果当前处于扫描状态，进行弹窗提示
    ScanStatus currentStatus = m_antivirusWork->getCurrentScanStatus();
    if (ScanStatus::Free != currentStatus) {
        showTipDialog();
        return;
    }

    m_antivirusWork->sendNotifyOpenVdbUpdateDialog();
}

// 更新版本号
void NatiavWidget::updateVersionUI(const QString sVersion)
{
    m_version->setText(sVersion);
}

// 检查更新/更新按钮点击槽
void NatiavWidget::updateButtonClicked()
{
    QCommandLinkButton *button = qobject_cast<QCommandLinkButton *>(sender());
    if (0 == button->property("flag")) {
        m_antivirusWork->updateVirusSrvVersion();
    } else {
        ScanStatus currentStatus = m_antivirusWork->getCurrentScanStatus();
        if (ScanStatus::Free != currentStatus) {
            showTipDialog();
            return;
        }

        if (m_antivirusWork->vdbVersionChecking()) {
            DialogManage dialogManage;
            DDialog *dialog = dialogManage.creatChangeAddressTipDialog();
            dialog->exec();
            return;
        }
        m_antivirusWork->requestUpdateVirusDb();
    }
    updataCheckingWaiting();
}

// 检查更新按钮转圈
void NatiavWidget::updataCheckingWaiting()
{
    // 隐藏检查更新/更新按钮，显示动态加载
    m_updateBtn->setVisible(false);
    m_spinner->start();
    m_spinner->show();
}

void NatiavWidget::usbAutoScan(bool isChecked)
{
    m_gsetting->SetValue(AUTO_SCAN_USB, isChecked);
}

void NatiavWidget::CnterViewClearFocus()
{
    QListView* w = qobject_cast<QListView*>(sender());
    w->clearFocus();
}
